<!-- src/views/Dashboard.vue -->
<template>
  <div class="dashboard">
    <!-- 顶部导航栏 -->
    <header class="dashboard-header">
      <div class="header-left">
        <h1 class="logo">🌐 VPN Manager</h1>
        <nav class="nav-menu">
          <router-link to="/dashboard" class="nav-item" :class="{ active: $route.path === '/dashboard' }">
            仪表板
          </router-link>
          <router-link to="/subscription" class="nav-item" :class="{ active: $route.path === '/subscription' }">
            订阅管理
          </router-link>
          <router-link to="/nodes" class="nav-item" :class="{ active: $route.path === '/nodes' }">
            节点列表
          </router-link>
          <router-link to="/usage" class="nav-item" :class="{ active: $route.path === '/usage' }">
            使用记录
          </router-link>
        </nav>
      </div>
      <div class="header-right">
        <div class="user-menu">
          <span class="user-name">{{ user?.email }}</span>
          <div class="user-avatar">
            {{ user?.email?.charAt(0).toUpperCase() }}
          </div>
          <button @click="logout" class="logout-btn">退出</button>
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="dashboard-main">
      <!-- 状态概览卡片 -->
      <div class="status-overview">
        <div class="status-card primary">
          <div class="status-icon">👤</div>
          <div class="status-info">
            <h3>账户状态</h3>
            <p :class="user?.is_active ? 'status-active' : 'status-inactive'">
              {{ user?.is_active ? '正常' : '禁用' }}
            </p>
          </div>
        </div>

        <div class="status-card success" v-if="currentSubscription">
          <div class="status-icon">📊</div>
          <div class="status-info">
            <h3>已用流量</h3>
            <p>{{ formatTraffic(currentSubscription.used_traffic_mb) }}</p>
          </div>
        </div>

        <div class="status-card warning" v-if="currentSubscription">
          <div class="status-icon">⏰</div>
          <div class="status-info">
            <h3>剩余时间</h3>
            <p>{{ getRemainingDays(currentSubscription.expires_at) }}天</p>
          </div>
        </div>

        <div class="status-card info">
          <div class="status-icon">🌐</div>
          <div class="status-info">
            <h3>当前节点</h3>
            <p>{{ currentNode?.name || '未选择' }}</p>
          </div>
        </div>
      </div>

      <div class="content-grid">
        <!-- 左侧：用户信息和订阅 -->
        <div class="left-column">
          <!-- 用户信息卡片 -->
          <div class="card user-info-card">
            <div class="card-header">
              <h2>👤 用户信息</h2>
              <span class="card-badge" :class="user?.is_active ? 'active' : 'inactive'">
                {{ user?.is_active ? '活跃' : '禁用' }}
              </span>
            </div>
            <div class="card-content">
              <div class="info-item">
                <label>邮箱地址</label>
                <p>{{ user?.email }}</p>
              </div>
              <div class="info-item">
                <label>用户姓名</label>
                <p>{{ user?.full_name || '未设置' }}</p>
              </div>
              <div class="info-item">
                <label>注册时间</label>
                <p>{{ formatDate(user?.created_at) }}</p>
              </div>
            </div>
          </div>

          <!-- 订阅信息卡片 -->
          <div class="card subscription-card">
            <div class="card-header">
              <h2>📋 订阅信息</h2>
              <span v-if="currentSubscription" class="card-badge success">
                有效
              </span>
              <span v-else class="card-badge danger">
                无订阅
              </span>
            </div>
            <div class="card-content">
              <div v-if="currentSubscription" class="subscription-details">
                <div class="info-item">
                  <label>套餐名称</label>
                  <p class="plan-name">{{ currentSubscription.subscription?.name || '标准套餐' }}</p>
                </div>
                <div class="info-item">
                  <label>到期时间</label>
                  <p class="expiry-date">{{ formatDate(currentSubscription.expires_at) }}</p>
                </div>
                <div class="info-item">
                  <label>流量限制</label>
                  <p>{{ formatTraffic(currentSubscription.subscription?.traffic_mb) }}</p>
                </div>
                <div class="info-item">
                  <label>已用流量</label>
                  <p>{{ formatTraffic(currentSubscription.used_traffic_mb) }}</p>
                </div>
                <div class="progress-bar">
                  <div class="progress-label">
                    <span>使用进度</span>
                    <span>{{ getUsagePercentage() }}%</span>
                  </div>
                  <div class="progress-track">
                    <div
                        class="progress-fill"
                        :style="{ width: getUsagePercentage() + '%' }"
                        :class="getUsagePercentage() > 80 ? 'warning' : 'normal'"
                    ></div>
                  </div>
                </div>
              </div>
              <div v-else class="no-subscription">
                <div class="empty-state">
                  <div class="empty-icon">📭</div>
                  <h3>暂无有效订阅</h3>
                  <p>立即购买套餐开启VPN服务</p>
                  <button @click="goToSubscription" class="primary-btn large">
                    购买套餐
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：配置和节点 -->
        <div class="right-column">
          <!-- WireGuard 配置卡片 -->
          <div class="card config-card" v-if="currentSubscription">
            <div class="card-header">
              <h2>🔧 WireGuard 配置</h2>
            </div>
            <div class="card-content">
              <div class="config-info">
                <div class="info-item">
                  <label>客户端IP</label>
                  <p class="ip-address">{{ configData?.client_ip || '未分配' }}</p>
                </div>
                <div class="config-actions">
                  <button @click="downloadConfig" class="action-btn primary">
                    <span class="btn-icon">📥</span>
                    下载配置
                  </button>
                  <button @click="toggleConfigPreview" class="action-btn secondary">
                    <span class="btn-icon">👁️</span>
                    {{ showConfigPreview ? '隐藏' : '预览' }}配置
                  </button>
                  <button @click="handleRefreshConfig" class="action-btn secondary">
                    <span class="btn-icon">🔄</span>
                    刷新IP
                  </button>
                </div>
              </div>

              <div v-if="showConfigPreview && configData" class="config-preview">
                <h4>配置文件内容</h4>
                <pre class="config-content">{{ configData.config_content }}</pre>
                <div class="config-tips">
                  <p>💡 提示：下载配置文件后，导入WireGuard客户端即可连接VPN</p>
                </div>
              </div>
            </div>
          </div>

          <!-- 节点列表卡片 -->
          <div class="card nodes-card">
            <div class="card-header">
              <h2>🌐 可用节点</h2>
              <span class="node-count">{{ nodes.length }} 个节点</span>
            </div>
            <div class="card-content">
              <div v-if="nodes.length > 0" class="nodes-list">
                <div
                    v-for="node in nodes"
                    :key="node.id"
                    class="node-item"
                    :class="{ 'current': node.id === currentNode?.id }"
                >
                  <div class="node-icon">
                    <span v-if="node.location.includes('北京')">🇨🇳</span>
                    <span v-else-if="node.location.includes('美国')">🇺🇸</span>
                    <span v-else-if="node.location.includes('英国')">🇬🇧</span>
                    <span v-else>🌐</span>
                  </div>
                  <div class="node-info">
                    <h4>{{ node.name }}</h4>
                    <p class="node-location">📍 {{ node.location }}</p>
                    <div class="node-stats">
                      <span class="load-indicator" :class="getLoadClass(node.load_percent)">
                        {{ node.load_percent }}% 负载
                      </span>
                      <span class="status-indicator" :class="node.is_active ? 'online' : 'offline'">
                        {{ node.is_active ? '在线' : '维护' }}
                      </span>
                    </div>
                  </div>
                  <button
                      @click="handleSwitchNode(node.id)"
                      :disabled="!node.is_active || node.id === currentNode?.id"
                      class="node-action-btn"
                      :class="{
                      'current': node.id === currentNode?.id,
                      'disabled': !node.is_active
                    }"
                  >
                    {{ getButtonText(node) }}
                  </button>
                </div>
              </div>
              <div v-else class="no-nodes">
                <div class="empty-state">
                  <div class="empty-icon">🔍</div>
                  <h3>暂无可用节点</h3>
                  <p>请稍后刷新或联系管理员</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import { getNodes, getWireGuardConfig, downloadWireGuardConfig, refreshWireGuardConfig, switchNode } from '@/api/vpn'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const nodes = ref([])
const configData = ref(null)
const showConfigPreview = ref(false)
const loading = ref(false)

// 计算属性
const user = computed(() => authStore.user)
const currentSubscription = computed(() => authStore.currentSubscription)
const currentNode = computed(() => {
  if (!currentSubscription.value || !nodes.value.length) return null
  return nodes.value.find(node => node.id === currentSubscription.value.node_id)
})

// 生命周期
onMounted(async () => {
  await loadData()
})

// 方法
const loadData = async () => {
  loading.value = true
  try {
    console.log('🔄 开始加载节点数据...')
    const nodesResponse = await getNodes()
    console.log('📊 节点API响应:', nodesResponse)

    if (nodesResponse.data && Array.isArray(nodesResponse.data)) {
      nodes.value = nodesResponse.data
      console.log(`✅ 成功加载 ${nodes.value.length} 个节点`)
    } else {
      console.warn('⚠️ 节点数据格式异常:', nodesResponse.data)
      // 使用模拟数据
      nodes.value = getMockNodes()
    }

    if (currentSubscription.value) {
      console.log('🔄 开始加载WireGuard配置...')
      const configResponse = await getWireGuardConfig(currentSubscription.value.id)
      configData.value = configResponse.data
      console.log('✅ WireGuard配置加载成功')
    }

    await authStore.fetchUserData()
    console.log('✅ 所有数据加载完成')

  } catch (error) {
    console.error('❌ 加载数据失败:', error)
    console.error('错误详情:', error.response?.data || error.message)

    // 使用模拟数据继续展示
    nodes.value = getMockNodes()
    alert('加载数据失败，使用模拟数据展示')
  } finally {
    loading.value = false
  }
}

// 模拟节点数据
const getMockNodes = () => {
  return [
    {
      id: 1,
      name: '北京节点',
      location: '中国北京',
      is_active: true,
      load_percent: 30,
      avg_latency: 45,
      current_users: 15,
      description: '高性能北京节点'
    },
    {
      id: 2,
      name: '香港节点',
      location: '中国香港',
      is_active: true,
      load_percent: 60,
      avg_latency: 80,
      current_users: 25,
      description: '稳定香港节点'
    },
    {
      id: 3,
      name: '美国节点',
      location: '美国洛杉矶',
      is_active: true,
      load_percent: 45,
      avg_latency: 150,
      current_users: 20,
      description: '美国洛杉矶节点'
    }
  ]
}

const downloadConfig = async () => {
  if (!currentSubscription.value) {
    alert('请先购买订阅套餐')
    return
  }

  try {
    const response = await downloadWireGuardConfig(currentSubscription.value.id)
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `wg-config-${currentNode.value?.name || 'config'}.conf`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载配置文件失败:', error)
    alert('下载配置文件失败，请重试')
  }
}

const toggleConfigPreview = () => {
  showConfigPreview.value = !showConfigPreview.value
}

const handleRefreshConfig = async () => {
  if (!currentSubscription.value) {
    alert('请先购买订阅套餐')
    return
  }

  loading.value = true
  try {
    console.log('🔄 开始刷新WireGuard配置...')

    // 调用刷新配置的API
    const response = await refreshWireGuardConfig(currentSubscription.value.id)
    console.log('刷新配置响应:', response)

    // 重新获取配置
    const configResponse = await getWireGuardConfig(currentSubscription.value.id)
    configData.value = configResponse.data

    alert('配置刷新成功！客户端IP已更新')
    console.log('✅ WireGuard配置刷新成功')

  } catch (error) {
    console.error('❌ 刷新配置失败:', error)
    console.error('错误详情:', error.response?.data)

    // 更详细的错误提示
    if (error.response?.status === 404) {
      alert('刷新配置功能暂不可用，请联系管理员')
    } else {
      alert(error.response?.data?.detail || '刷新配置失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

const handleSwitchNode = async (nodeId) => {
  if (!currentSubscription.value) {
    alert('请先购买订阅套餐')
    return
  }

  const selectedNode = nodes.value.find(node => node.id === nodeId)
  if (!selectedNode) {
    alert('节点不存在')
    return
  }

  if (!confirm(`确定要切换到 ${selectedNode.name} 节点吗？切换后需要重新下载配置文件。`)) {
    return
  }

  loading.value = true
  try {
    console.log(`🔄 开始切换到节点 ${nodeId}...`)
    // 使用完整的API调用
    const response = await switchNode(currentSubscription.value.id, nodeId)

    // 更新当前订阅信息
    await authStore.fetchUserData()

    // 重新加载配置
    const configResponse = await getWireGuardConfig(currentSubscription.value.id)
    configData.value = configResponse.data

    alert('节点切换成功！请重新下载配置文件')
    console.log('✅ 节点切换成功')

  } catch (error) {
    console.error('❌ 切换节点失败:', error)
    console.error('错误详情:', error.response?.data)
    alert(error.response?.data?.detail || '切换节点失败，请重试')
  } finally {
    loading.value = false
  }
}

const goToSubscription = () => {
  router.push('/subscription')
}

const logout = () => {
  authStore.clearToken()
  router.push('/login')
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const formatTraffic = (mb) => {
  if (!mb) return '0 MB'
  if (mb < 1024) return `${mb} MB`
  return `${(mb / 1024).toFixed(2)} GB`
}

const getRemainingDays = (expiryDate) => {
  if (!expiryDate) return 0
  const now = new Date()
  const expiry = new Date(expiryDate)
  const diffTime = expiry - now
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays > 0 ? diffDays : 0
}

const getUsagePercentage = () => {
  if (!currentSubscription.value || !currentSubscription.value.subscription?.traffic_mb) return 0
  const total = currentSubscription.value.subscription.traffic_mb
  const used = currentSubscription.value.used_traffic_mb || 0
  return Math.min(100, Math.round((used / total) * 100))
}

const getLoadClass = (load) => {
  if (load < 30) return 'low'
  if (load < 70) return 'medium'
  return 'high'
}

const getButtonText = (node) => {
  if (node.id === currentNode.value?.id) return '当前节点'
  if (!node.is_active) return '维护中'
  return '切换节点'
}
</script>

<style scoped>
/* 原有的所有样式保持不变 */
.dashboard {
  min-height: 100vh;
  background: #f5f7fa;
}

.dashboard-header {
  background: white;
  padding: 0 30px;
  border-bottom: 1px solid #e1e5e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 40px;
}

.logo {
  font-size: 20px;
  font-weight: 700;
  color: #1890ff;
  margin: 0;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.nav-item {
  text-decoration: none;
  color: #666;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s;
}

.nav-item.active {
  background: #1890ff;
  color: white;
}

.nav-item:hover:not(.active) {
  background: #f0f0f0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-menu {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-name {
  color: #333;
  font-weight: 500;
}

.user-avatar {
  width: 36px;
  height: 36px;
  background: #1890ff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.logout-btn {
  padding: 6px 12px;
  border: 1px solid #dc3545;
  background: white;
  color: #dc3545;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.logout-btn:hover {
  background: #dc3545;
  color: white;
}

.dashboard-main {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.status-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.status-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border-left: 4px solid;
}

.status-card.primary {
  border-left-color: #1890ff;
}

.status-card.success {
  border-left-color: #52c41a;
}

.status-card.warning {
  border-left-color: #faad14;
}

.status-card.info {
  border-left-color: #13c2c2;
}

.status-icon {
  font-size: 32px;
}

.status-info h3 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #666;
}

.status-info p {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #333;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

@media (max-width: 1200px) {
  .content-grid {
    grid-template-columns: 1fr;
  }
}

.card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
}

.card-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.card-badge.active {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.card-badge.inactive {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.card-badge.success {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.card-badge.danger {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.card-content {
  padding: 24px;
}

.info-item {
  margin-bottom: 16px;
}

.info-item label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.info-item p {
  margin: 0;
  color: #333;
  font-weight: 500;
}

.plan-name {
  color: #1890ff;
  font-size: 16px;
  font-weight: 700;
}

.expiry-date {
  color: #faad14;
  font-weight: 700;
}

.ip-address {
  font-family: 'Courier New', monospace;
  background: #f5f5f5;
  padding: 4px 8px;
  border-radius: 4px;
  color: #d48806;
}

.progress-bar {
  margin-top: 20px;
}

.progress-label {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.progress-track {
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s;
}

.progress-fill.normal {
  background: linear-gradient(90deg, #52c41a, #73d13d);
}

.progress-fill.warning {
  background: linear-gradient(90deg, #faad14, #ffc53d);
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  color: #333;
}

.empty-state p {
  margin: 0 0 20px 0;
  color: #666;
}

.primary-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s;
}

.primary-btn:hover {
  background: #40a9ff;
  transform: translateY(-1px);
}

.primary-btn.large {
  padding: 12px 24px;
  font-size: 14px;
}

.action-btn {
  padding: 8px 16px;
  border: 1px solid;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.action-btn.primary {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.action-btn.primary:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}

.action-btn.secondary {
  background: white;
  color: #666;
  border-color: #d9d9d9;
}

.action-btn.secondary:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.config-actions {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  flex-wrap: wrap;
}

.config-preview {
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.config-preview h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.config-content {
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 12px;
  line-height: 1.4;
  background: white;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  max-height: 200px;
  overflow-y: auto;
}

.config-tips {
  margin-top: 12px;
  padding: 8px 12px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  font-size: 12px;
  color: #0050b3;
}

.node-count {
  font-size: 12px;
  color: #666;
}

.nodes-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.node-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s;
}

.node-item.current {
  border-color: #1890ff;
  background: #f0f8ff;
}

.node-item:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.node-icon {
  font-size: 24px;
}

.node-info {
  flex: 1;
}

.node-info h4 {
  margin: 0 0 4px 0;
  color: #333;
}

.node-location {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 12px;
}

.node-stats {
  display: flex;
  gap: 12px;
}

.load-indicator, .status-indicator {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 500;
}

.load-indicator.low {
  background: #f6ffed;
  color: #52c41a;
}

.load-indicator.medium {
  background: #fff7e6;
  color: #fa8c16;
}

.load-indicator.high {
  background: #fff2f0;
  color: #ff4d4f;
}

.status-indicator.online {
  background: #f6ffed;
  color: #52c41a;
}

.status-indicator.offline {
  background: #fff2f0;
  color: #ff4d4f;
}

.node-action-btn {
  padding: 6px 16px;
  border: 1px solid #1890ff;
  background: white;
  color: #1890ff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.node-action-btn:hover:not(.current):not(.disabled) {
  background: #1890ff;
  color: white;
}

.node-action-btn.current {
  background: #52c41a;
  color: white;
  border-color: #52c41a;
  cursor: default;
}

.node-action-btn.disabled {
  background: #f5f5f5;
  color: #d9d9d9;
  border-color: #d9d9d9;
  cursor: not-allowed;
}
</style>